package com.caocaog.market.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.merchant.entity.MkMerchantCert;
import com.caocaog.market.merchant.mapper.MkMerchantCertMapper;
import com.caocaog.market.merchant.service.IMkMerchantCertService;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Optional;

/**
 * @Description: 商户支付证书
 * @Author: jeecg-boot
 * @Date: 2024-04-03
 * @Version: V1.0
 */
@Service
public class MkMerchantCertServiceImpl extends ServiceImpl<MkMerchantCertMapper, MkMerchantCert> implements IMkMerchantCertService {

    /**
     * 上传商户的支付证书信息
     *
     * @param certFile   支付证书文件
     * @param merchantId 商户ID
     */
    @Override
    public void saveMerchantCert(MultipartFile certFile, String merchantId) {
        MkMerchantCert mkMerchantCert = new MkMerchantCert();
        mkMerchantCert.setDelFlag("1");
        try {
            mkMerchantCert.setCertFile(certFile.getBytes());
        } catch (Exception e) {
            log.error("读取证书数据信息失败！");
            throw new JeecgBootException(e);
        }
        mkMerchantCert.setMerchantId(merchantId);
        try {
            save(mkMerchantCert);
        } catch (Exception e) {
            log.error("当前商户已经存在证书文件！");
            throw new JeecgBootException("当前商户已经存在证书文件");
        }
    }

    /**
     * 更新商户的证书信息
     *
     * @param certFile   证书文件
     * @param merchantId 商户ID
     */
    @Override
    public void updateMerchantCert(MultipartFile certFile, String merchantId) {
        MkMerchantCert merchantCert = getByMid(merchantId);
        if (merchantCert == null) {
            saveMerchantCert(certFile, merchantId);
            return;
        }
        try {
            merchantCert.setCertFile(certFile.getBytes());
        } catch (IOException e) {
            log.error("读取证书文件信息失败！");
            throw new JeecgBootException(e);
        }
        updateById(merchantCert);


    }

    /**
     * 根据商户ID查询出商户的证书信息
     *
     * @param mid 商户ID
     * @return 查询到的证书信息
     */
    @Override
    public MkMerchantCert getByMid(String mid) {
        return getOne(new LambdaQueryWrapper<MkMerchantCert>().eq(MkMerchantCert::getMerchantId, mid));
    }
}
